﻿#include "ess_single.h"
#define ASMORDERDBSTR ConnectPoolFactory::getInstance()->getConnectPool(ConnectPoolFactory::AsmOrderDataBase)

ESS_Single* ESS_Single::ESS_SingleItiem=0;
QMutex ESS_Single::mutex;

ESS_Single::ESS_Single(QObject *parent)
{
    initStationStatus();    //初始化先马站点状态

    // 容器写入数据
    Map_write();
}

void ESS_Single::setCurrentServerItem(ServerItem CServerItem, ServerInit CServerInit)
{
    ServerInitItem=CServerInit;
    CurrentServerItem=CServerItem;
}

void ESS_Single::setStationInfoMap(QMap<QString, deviceI> stationInfoMapI)
{
    stationInfoMap=stationInfoMapI;
}

QMap<QString, deviceI> ESS_Single::getstationInfoMap_Map()
{
    return stationInfoMap;
}

bool ESS_Single::setRunTask(QString taskId, int action)
{
    if(taskId!=""){
        RunTask_Client.insert(taskId,action);    //设置平板放行链表
        qDebug()<<"设置平板放行链表--->taskId:"<<taskId<<" agvNum:"<<action;
        return true;
    }
    return false;
}

int ESS_Single::getMESRunTask(QString taskId)
{
    int action=-1;
    if(RunTask_Client.contains(taskId)){
        action=RunTask_Client.find(taskId).value();
        RunTask_Client.remove(taskId);
        qDebug()<<"获取平板放行链表--->getMESRunTask----->taskId:"<<taskId<<"  action:"<<action<<" size:"<<RunTask_Client.size();
    }
    return action;//放行的类型:0直接放行，1放行后需要返空料箱
}

bool ESS_Single::setRunTaskMap(QString taskId, RunTaskData RunTaskDataI)
{
    if(taskId!=""){
        RunTaskMap.insert(taskId, RunTaskDataI);    //设置平板放行链表
        qDebug()<<"设置平板放行链表---setRunTaskMap--->taskId:"<<taskId<<" status:"<<RunTaskDataI.status<<" RunStation:"<<RunTaskDataI.RunStation;
        return true;
    }
    return false;
}

RunTaskData ESS_Single::getMESRunTaskMap(QString taskId)
{
    RunTaskData RunTaskDataI;
    if(RunTaskMap.contains(taskId)){
        RunTaskDataI=RunTaskMap.find(taskId).value();
        RunTaskMap.remove(taskId);
        qDebug()<<"获取平板放行链表---getMESRunTaskMap--->taskId:"<<taskId<<" status:"<<RunTaskDataI.status
               <<" RunStation:"<<RunTaskDataI.RunStation<<" size:"<<RunTaskMap.size();
    }
    return RunTaskDataI;
}

bool ESS_Single::setNewSAPExcelInfoList(SAPExcelInfo SAPExcelInfoI)
{
    if(!newSAPExcelInfoList.contains(SAPExcelInfoI.taskId)){
        newSAPExcelInfoList.insert(SAPExcelInfoI.taskId,SAPExcelInfoI);
        return true;
    }
    return false;
}

QMap<QString, SAPExcelInfo> ESS_Single::getNewSAPExcelInfoList()
{
    QMap<QString, SAPExcelInfo>newSAPExcelInfoListI;
    newSAPExcelInfoListI=newSAPExcelInfoList;
    newSAPExcelInfoList.clear();
    return newSAPExcelInfoListI;

}

//获取SAP任务链表
void ESS_Single::setCurrentSAPExcelInfoTask(QMap<int, SAPExcelInfo> seletSAPExcelInfoTask_)
{
    seletSAPExcelInfoTask=seletSAPExcelInfoTask_;
}

QMap<int, SAPExcelInfo> ESS_Single::getCurrentSAPExcelInfoTask()
{
    return  seletSAPExcelInfoTask;
}

void ESS_Single::setAGVCurrentTaskMap(QMap<QString, AGVCurrentTask> AGVCurrentTaskMap_)
{
    AGVCurrentTaskMap=AGVCurrentTaskMap_;
}

QMap<QString, AGVCurrentTask> ESS_Single::getAGVCurrentTaskMap()
{
    return AGVCurrentTaskMap;
}

QMap<QString, shelfBinInfo> ESS_Single::getshelfBinInfoMap(QString taskType,QString queryLineEdit,QString containerCode)
{
    QMap<QString, shelfBinInfo> shelfBinInfoMap_;
    connectBuilder build(ASMORDERDBSTR);
    QSqlDatabase sqlDatabase =  build.getOpenDatabase();
    QSqlQuery sqlQuery(sqlDatabase);
    sqlQuery.setForwardOnly(true);

    if(taskType==""){
        sqlQuery.prepare("select * from shelfInfo ;");
    }if(taskType=="shelfBindesc"){
        sqlQuery.prepare("select * from shelfInfo where shelfBindesc =:shelfBindesc ;");
        sqlQuery.addBindValue(queryLineEdit);
    }if(taskType=="podId"){
        sqlQuery.prepare("select * from shelfInfo where podId =:podId ;");
        sqlQuery.addBindValue(queryLineEdit);
    }if(taskType=="LabelNo"){
        sqlQuery.prepare("select * from shelfInfo where LabelNo =:LabelNo ;");
        sqlQuery.addBindValue(queryLineEdit);
    }if(taskType=="containerCode"){
        sqlQuery.prepare("select * from shelfInfo where containerCode =:containerCode ;");
        sqlQuery.addBindValue(containerCode);
    }

    if(sqlQuery.exec())
    {
        while(sqlQuery.next())
        {
            shelfBinInfo shelfBinInfoI;
            shelfBinInfoI.shelfBinIndex=sqlQuery.value("shelfBinIndex").toInt();        //所属架位索引
            shelfBinInfoI.shelfBindesc=sqlQuery.value("shelfBindesc").toString();       //所属架位注释
            shelfBinInfoI.podId=sqlQuery.value("podId").toString();                        //货架编号
            shelfBinInfoI.podIdDesc=sqlQuery.value("podIdDesc").toString();             //货架注释

            shelfBinInfoI.containerIndex=sqlQuery.value("containerIndex").toInt();      //容器编码索引 ->唯一
            shelfBinInfoI.containerCode=sqlQuery.value("containerCode").toString();     //容器编码 (即胶箱编码) ->唯一
            shelfBinInfoI.SAPTaskIndex=sqlQuery.value("SAPTaskIndex").toInt();
            shelfBinInfoI.LabelNo=sqlQuery.value("LabelNo").toString();                 //工单凭证号

            shelfBinInfoI.binEnable=sqlQuery.value("binEnable").toInt();                //使用/禁用
            shelfBinInfoI.showEnable=sqlQuery.value("showEnable").toInt();              //是否显示
            shelfBinInfoI.setFull=sqlQuery.value("setFull").toInt();                    //0未满  1已满
            shelfBinInfoI.status=sqlQuery.value("status").toInt();                      //0 空闲  1任务占用中

            shelfBinInfoI.layer=sqlQuery.value("layer").toInt();                        //第几层
            shelfBinInfoI.side=sqlQuery.value("side").toInt();                          //A,B 面

            shelfBinInfoI.volume=sqlQuery.value("volume").toDouble();                   //Bin的体积 14升
            shelfBinInfoI.allvolume=sqlQuery.value("allvolume").toDouble();             //总体积

            shelfBinInfoI.percent=sqlQuery.value("percent").toDouble();                 //占用 %
            shelfBinInfoI.realqty=sqlQuery.value("realqty").toDouble();                 //实际存放数量

            shelfBinInfoI.weight=sqlQuery.value("weight").toDouble();                   //实际存放重量
            shelfBinInfoI.maxweight=sqlQuery.value("maxweight").toDouble();             //最大存放重量

            if(!shelfBinInfoMap_.contains(shelfBinInfoI.shelfBindesc)){
                shelfBinInfoMap_.insert(shelfBinInfoI.shelfBindesc,shelfBinInfoI);
                //qDebug()<<shelfBinInfoI.shelfBinIndex<<shelfBinInfoI.shelfBindesc<<shelfBinInfoI.podId<<shelfBinInfoI.podIdDesc;
            }
        }
    }

    if(!shelfBinInfoMap_.isEmpty()){
        shelfBinInfoMap=shelfBinInfoMap_;
    }

    return shelfBinInfoMap_;
}

//入库时获取空闲的 库位
shelfBinInfo ESS_Single::getshelfBinInfo_Empty(SAPExcelInfo SAPExcelInfoI)
{
    shelfBinInfo shelfBinInfoI;

    return shelfBinInfoI;
}

//出库时获取当前胶箱库位
shelfBinInfo ESS_Single::getcontainerCode_desc(QString containerCode)
{
    shelfBinInfo shelfBinInfoI;
    QMap<QString,shelfBinInfo >::iterator iter=shelfBinInfoMap.begin();
    while (iter!=shelfBinInfoMap.end()) {
        if(iter.value().containerCode == containerCode && containerCode!=""){
            shelfBinInfoI=iter.value();
        }
        iter++;
    }
    return shelfBinInfoI;
}

void ESS_Single::setLiftCodeMap(QMap<QString, LiftCode> LiftCodeMap_)
{
    LiftCodeMap=LiftCodeMap_;
}

QMap<QString, LiftCode> ESS_Single::getLiftCodeMap()
{
    if(LiftCodeMap.isEmpty()){
        LiftCodeMap=CurrentServerItem.LiftCodeMap;
    }
    return LiftCodeMap;
}

QMap<int, CodeStatus> ESS_Single::getCodeStatusMap()
{
     QMap<int,CodeStatus>CodeStatusMap;                     //MES 的所有位置状态
     QMap<int,email_message> syserror_messageMap;
     connectBuilder build(ASMORDERDBSTR);
     QSqlDatabase sqlDatabase =  build.getOpenDatabase();
     QSqlQuery sqlQuery1(sqlDatabase);
     sqlQuery1.prepare("select * from CodeStatus ;");

     if(sqlQuery1.exec())
     {
         while(sqlQuery1.next())
         {
             CodeStatus CodeStatusI;
             CodeStatusI.Station=sqlQuery1.value("Station").toInt();                //站点                                AGV站点，其它老化 房的站点为1－26，上料位为27，下料位为28
             CodeStatusI.Room=sqlQuery1.value("Room").toInt();                      //房间状态                             0表示不确，1表示有车，2表示无车
             CodeStatusI.Result=sqlQuery1.value("Result").toInt();                  //老化结果                             老化完成后此字段会写入1，其他状态写入0

             CodeStatusI.CarCode=sqlQuery1.value("CarCode").toInt();                //车编码
             CodeStatusI.CarStauts=sqlQuery1.value("CarStauts").toInt();            //车状态(0未知  1空车架   2满车架)        上料位和下料位由捷思特提供信息，其它位置由AGV自行决定。
             CodeStatusI.Locked=sqlQuery1.value("Locked").toInt();                  //锁定(0解锁  1锁定   2满车架)          有任务时 AGV会锁定
             CodeStatusI.WaitCheck=sqlQuery1.value("WaitCheck").toInt();            //等待放行状态   0空闲 1AGV等待放行     2MES写入放行  0空闲

             CodeStatusI.deviceDesc=sqlQuery1.value("deviceDesc").toString();       //站点名称
             CodeStatusI.StationDesc=sqlQuery1.value("StationDesc").toString();     //站点名称
             CodeStatusI.StationType=sqlQuery1.value("StationType").toString();     //站点类型  load unload station
             CodeStatusI.SAPTaskIndex=sqlQuery1.value("SAPTaskIndex").toInt();      //任务索引 唯一值
             CodeStatusI.taskId=sqlQuery1.value("taskId").toString();               //任务编码 唯一性
             CodeStatusI.taskStatus=sqlQuery1.value("taskStatus").toInt();          //AGV任务状态
             CodeStatusI.agvNum=sqlQuery1.value("agvNum").toInt();                  //小车号

             CodeStatusI.x01=sqlQuery1.value("x01").toInt();
             CodeStatusI.y01=sqlQuery1.value("y01").toInt();
             CodeStatusI.x02=sqlQuery1.value("x02").toInt();
             CodeStatusI.y02=sqlQuery1.value("y02").toInt();

             CodeStatusI.Priority=sqlQuery1.value("Priority").toInt();
             CodeStatusI.upDateDesc=sqlQuery1.value("upDateDesc").toString();        //任务更新 内容
             CodeStatusI.statusTimer=sqlQuery1.value("statusTimer").toDateTime();    //在卸货点 超时默认完成

             CodeStatusMap.insert(CodeStatusI.Station,CodeStatusI);

             //qDebug()<<"CodeStatusI -->Station"<<CodeStatusI.StationDesc<< CodeStatusI.upDateDesc<< CodeStatusI.statusTimer.toString("MM-dd hh:mm:ss");

         }
     }else {
         qDebug() << sqlQuery1.lastQuery();
     }

     return CodeStatusMap;
}

bool ESS_Single::setCodeStatus_SAP(QList<CodeStatus>CodeStatusList)
{
    connectBuilder build(ASMORDERDBSTR);
    QSqlDatabase sqlDatabase =  build.getOpenDatabase();
    QSqlQuery sqlQuery(sqlDatabase);

    for(int i=0;i<CodeStatusList.size();i++){

        QString upDateDesc="AGV-- Locked:"+QString::number(CodeStatusList[i].Locked)
                +" SAPTaskIndex:"+QString::number(CodeStatusList[i].SAPTaskIndex)
                +" agvNum:"+QString::number(CodeStatusList[i].agvNum)
                +" CarCode:"+QString::number(CodeStatusList[i].CarCode)
                +" CarStauts:"+QString::number(CodeStatusList[i].CarStauts);

        sqlQuery.prepare("UPDATE [dbo].[CodeStatus] SET [Locked]=:Locked,"
                         "[SAPTaskIndex]=:SAPTaskIndex,[agvNum]=:agvNum,"
                         "[CarCode]=:CarCode,[CarStauts]=:CarStauts,[Priority]=:Priority,"
                         "[upDateDesc]=:upDateDesc,[statusTimer]=:statusTimer "
                         "WHERE [Station]=:Station;");

        sqlQuery.addBindValue(CodeStatusList[i].Locked);
        sqlQuery.addBindValue(CodeStatusList[i].SAPTaskIndex);
        sqlQuery.addBindValue(CodeStatusList[i].agvNum);
        sqlQuery.addBindValue(CodeStatusList[i].CarCode);
        sqlQuery.addBindValue(CodeStatusList[i].CarStauts);
        sqlQuery.addBindValue(CodeStatusList[i].Priority);
        sqlQuery.addBindValue(upDateDesc);
        sqlQuery.addBindValue(QDateTime::currentDateTime()); //在卸货点 超时默认完成
        sqlQuery.addBindValue(CodeStatusList[i].Station);

        if(sqlQuery.exec()){
            qDebug()<<"setCodeStatus S--->Station"<<CodeStatusList[i].Station<<" Locked:"<<CodeStatusList[i].Locked<<" SAPTaskIndex:"<<CodeStatusList[i].SAPTaskIndex
                   <<" agvNum:"<<CodeStatusList[i].agvNum<<" CarCode:"<<CodeStatusList[i].CarCode<<" CarStauts:"<<CodeStatusList[i].CarStauts;
        }else {
            qDebug()<<"setCodeStatus E--->Station"<<CodeStatusList[i].Station<<" Locked:"<<CodeStatusList[i].Locked<<" SAPTaskIndex:"<<CodeStatusList[i].SAPTaskIndex
                   <<" agvNum:"<<CodeStatusList[i].agvNum<<" CarCode:"<<CodeStatusList[i].CarCode<<" CarStauts:"<<CodeStatusList[i].CarStauts;
        }

    }

    return true;

}

CodeStatus ESS_Single::getCodeStatus_CarRun(QString deviceDesc)
{
    CodeStatus CodeStatusI;
    connectBuilder build(ASMORDERDBSTR);
    QSqlDatabase sqlDatabase =  build.getOpenDatabase();
    QSqlQuery sqlQuery1(sqlDatabase);
    sqlQuery1.prepare("select * from CodeStatus where  deviceDesc =:deviceDesc;");
    sqlQuery1.addBindValue(deviceDesc);

    if(sqlQuery1.exec())
    {
        while(sqlQuery1.next())
        {

            CodeStatusI.Station=sqlQuery1.value("Station").toInt();                //站点                                AGV站点，其它老化 房的站点为1－26，上料位为27，下料位为28
            CodeStatusI.Room=sqlQuery1.value("Room").toInt();                      //房间状态                             0表示不确，1表示有车，2表示无车
            CodeStatusI.Result=sqlQuery1.value("Result").toInt();                  //老化结果                             老化完成后此字段会写入1，其他状态写入0

            CodeStatusI.CarCode=sqlQuery1.value("CarCode").toInt();                //车编码
            CodeStatusI.CarStauts=sqlQuery1.value("CarStauts").toInt();            //车状态(0未知  1空车架   2满车架)        上料位和下料位由捷思特提供信息，其它位置由AGV自行决定。
            CodeStatusI.Locked=sqlQuery1.value("Locked").toInt();                  //锁定(0解锁  1锁定   2满车架)          有任务时 AGV会锁定
            CodeStatusI.WaitCheck=sqlQuery1.value("WaitCheck").toInt();            //等待放行状态   0空闲 1AGV等待放行     2MES写入放行  0空闲


            CodeStatusI.deviceDesc=sqlQuery1.value("deviceDesc").toString();       //站点名称
            CodeStatusI.StationDesc=sqlQuery1.value("StationDesc").toString();     //站点名称
            CodeStatusI.StationType=sqlQuery1.value("StationType").toString();     //站点类型  load unload station
            CodeStatusI.SAPTaskIndex=sqlQuery1.value("SAPTaskIndex").toInt();      //任务索引 唯一值
            CodeStatusI.taskId=sqlQuery1.value("taskId").toString();               //任务编码 唯一性
            CodeStatusI.taskStatus=sqlQuery1.value("taskStatus").toInt();          //AGV任务状态
            CodeStatusI.agvNum=sqlQuery1.value("agvNum").toInt();                  //小车号

        }
    }else {
        qDebug() << sqlQuery1.lastQuery();
    }

    return CodeStatusI;
}

bool ESS_Single::setCodeStatus_CarRun(CodeStatus CodeStatusI)
{
    connectBuilder build(ASMORDERDBSTR);
    QSqlDatabase sqlDatabase =  build.getOpenDatabase();
    QSqlQuery sqlQuery(sqlDatabase);

    sqlQuery.prepare("UPDATE [dbo].[CodeStatus] SET [WaitCheck]=:WaitCheck "
                     "WHERE [Station]=:Station;");

    sqlQuery.addBindValue(CodeStatusI.WaitCheck);       //等待放行状态   0空闲 1AGV等待放行     2MES写入放行  0空闲
    sqlQuery.addBindValue(CodeStatusI.Station);         //站点

    if(sqlQuery.exec()){
        qDebug()<<"更新上下位机的放行信息 S--->Station"<<CodeStatusI.Station<<" WaitCheck:"<<CodeStatusI.WaitCheck;
    }else {
        qDebug()<<"更新上下位机的放行信息 E--->Station"<<CodeStatusI.Station<<" WaitCheck:"<<CodeStatusI.WaitCheck;
    }
    return true;
}

void ESS_Single::setModbusAllData(ModbusAll ModbusAllData)
{
    _ModbusAllData=ModbusAllData;
}

ModbusAll ESS_Single::getModbusAllData()
{
    return _ModbusAllData;
}


ESS_Request ESS_Single::setESS_RequestI(SAPExcelInfo SAPExcelInfoI, ESS_Request ESS_RequestI,QString actionId,int taskAgvNum,int WaitStation)
{
    QMap<int ,sapPath >::iterator iter=ServerInitItem.sapPathMap.begin();
    while (iter !=ServerInitItem.sapPathMap.end()) {//
        if(actionId==iter.value().Type){
            ESS_RequestI.pathId=iter.value().Id;
            ESS_RequestI.actionId=iter.value().Type;
        }
        iter++;
    }

    //任务类型  OUT-出库  IN-入库  MOVE-移库  Empty-返空箱
    if(ESS_RequestI.actionId=="action1"){//创建AGV 任务
        ESS_RequestI.taskType=SAPExcelInfoI.taskType;
        ESS_RequestI.taskId=SAPExcelInfoI.taskId_ess;

        ESS_RequestI.ESS_AGV0.agvId=taskAgvNum;                             //AGV编号
        ESS_RequestI.ESS_AGV0.taskId=SAPExcelInfoI.taskId_ess;              //订单编码唯一

        ESS_RequestI.ESS_AGV0.priority=SAPExcelInfoI.Priority;              //优先级

        deviceI loadI; deviceI unloadI;
        ESS_RequestI.ESS_AGV0.taskType=1;


        loadI=ServerInitItem.StationInfoMap.find(SAPExcelInfoI.load).value();
        unloadI=ServerInitItem.StationInfoMap.find(SAPExcelInfoI.unload).value();

        //1
        // load(起始点顶升)--->load(等待放行)--->unloadWaitNode--->unload(等待放行)---->load(返回起始站点)--->load(起始站点下降)---->返回待机

        //3
        // load--->loadWaitNode--->unloadWaitNode--->unload


        //起始站点
        ESS_RequestI.ESS_AGV0.load=loadI.Currentpoint;                 //取货站点
        ESS_RequestI.ESS_AGV0.loadWaitNode=loadI.Currentpoint;         //取货站点等待点
        ESS_RequestI.ESS_AGV0.loadAnglePose=loadI.anglePose;           //取货站点姿态角度
        ESS_RequestI.ESS_AGV0.loadAngleRotary=loadI.angleRotary;       //取货站点顶盘角度

        ESS_RequestI.ESS_AGV0.finishNode=loadI.Currentpoint;           //任务完成返回的待机点

        //卸货站点
        ESS_RequestI.ESS_AGV0.unload=unloadI.Currentpoint;             //目标站点
        ESS_RequestI.ESS_AGV0.unloadWaitNode=unloadI.waitPoint;        //目标站点等待点
        ESS_RequestI.ESS_AGV0.unloadAnglePose=unloadI.anglePose;       //目标站点姿态角度
        ESS_RequestI.ESS_AGV0.unloadAngleRotary=unloadI.angleRotary;   //目标站点顶盘角度


    }
    if(ESS_RequestI.actionId=="action3"){
        ESS_RequestI.ESS_AGV0.taskId=ESS_RequestI.taskId;                  //订单编码唯一
        ESS_RequestI.ESS_AGV0.agvId=ESS_RequestI.agvId;                    //AGV编号
        ESS_RequestI.WaitStation=WaitStation;
    }

    if(ESS_RequestI.actionId=="action5"){
        ESS_RequestI.ESS_AGV0.taskType=5;
    }


    if(ESS_RequestI.pathId!=0){
        ESS_RequestI.iKey=ESS_RequestI.taskId;
        if(ESS_RequestI.actionId=="action0"){ //机器人状态查询
            sapMsgInterface::getInstance()->robotCodes_query(ESS_RequestI.iKey,ESS_RequestI,currentUserNuber,ESS_RequestI.pathId);
        }if(ESS_RequestI.actionId=="action1"){//创建AGV 任务
            sapMsgInterface::getInstance()->taskCodes_actionId(ESS_RequestI.iKey,ESS_RequestI,currentUserNuber,ESS_RequestI.pathId,"agvTask");
        }if(ESS_RequestI.actionId=="action3"){ //给AGV下发放行指令
            sapMsgInterface::getInstance()->taskCodes_actionId(ESS_RequestI.iKey,ESS_RequestI,currentUserNuber,ESS_RequestI.pathId,"agvRun");
        }if(ESS_RequestI.actionId=="action5"){ //给AGV当个移动指令
            sapMsgInterface::getInstance()->taskCodes_actionId(ESS_RequestI.iKey,ESS_RequestI,currentUserNuber,ESS_RequestI.pathId,"agvMove");
        }if(ESS_RequestI.actionId=="WS01"){
            sapMsgInterface::getInstance()->taskCodes_MES(ESS_RequestI.iKey,ESS_RequestI,currentUserNuber,ESS_RequestI.pathId);
        }if(ESS_RequestI.actionId=="WS02"){
            sapMsgInterface::getInstance()->taskCodes_MES(ESS_RequestI.iKey,ESS_RequestI,currentUserNuber,ESS_RequestI.pathId);
        }if(ESS_RequestI.actionId=="action6"){ //摄像头查询库位状态动作
            sapMsgInterface::getInstance()->cameraCodes_query_Get(ESS_RequestI.iKey,-1,ESS_RequestI.pathId);
        }
    }

    qDebug()<<"setESS_RequestI---> actionId:"<<ESS_RequestI.actionId<<" taskAgvNum:"<<taskAgvNum<<" pathId:"<<ESS_RequestI.pathId
           <<" taskType:"<<ESS_RequestI.ESS_AGV0.taskType
           <<" taskId:"<<ESS_RequestI.ESS_AGV0.taskId<<" load:"<<ESS_RequestI.ESS_AGV0.load
           <<" workStation:"<<ESS_RequestI.ESS_AGV0.workStation<<" unload:"<<ESS_RequestI.ESS_AGV0.unload
           <<" WaitStation"<<WaitStation;

    return ESS_RequestI;
}


bool ESS_Single::setCurrentESS_Repost( QString taskId_ess,QString eventCodeDesc)
{
    CurrentESS_RepostMap.insert(taskId_ess,eventCodeDesc);
    qDebug()<<"----> taskId_ess:"<<taskId_ess<<" eventCodeDesc:"<<eventCodeDesc<<" size:"<<CurrentESS_RepostMap.size();
    return true;
}

QString ESS_Single::getCurrentESS_Repost(QString taskId_ess)
{
    QString eventCodeDesc="";
    if(CurrentESS_RepostMap.contains(taskId_ess)){
         eventCodeDesc=CurrentESS_RepostMap.value(taskId_ess);
         CurrentESS_RepostMap.remove(taskId_ess);
    }
    return eventCodeDesc;
}

WWYLPOST ESS_Single::MES_WWYLPOSTI(SAPExcelInfo SAPExcelInfoI, QString actionId)
{
    WWYLPOST WWYLPOST1;
    WWYLPOST1.actionId=actionId;
    WWYLPOST1.taskId=SAPExcelInfoI.taskId;                          //任务唯一编码
    WWYLPOST1.taskType=SAPExcelInfoI.taskType;                      //任务类型(OUT 出库，MOVE 点对点IN 入库)
    WWYLPOST1.boxNo=SAPExcelInfoI.containerCode;
    WWYLPOST1.proNo=SAPExcelInfoI.LabelNo;
    WWYLPOST1.taskType=SAPExcelInfoI.taskType;

    WWYLPOST1.taskStatus=QString::number(SAPExcelInfoI.taskStatus); //任务状态
    WWYLPOST1.taskStatusDesc=SAPExcelInfoI.taskStatusDesc;          //任务状态

//    qDebug()<<" 给MES 更新任务状态信息:"<<WWYLPOST1.actionId<<WWYLPOST1.operate<<WWYLPOST1.boxNo<<WWYLPOST1.pcbList
//           <<WWYLPOST1.resultStatus<<" SAPTaskIndex:"<<SAPExcelInfoI.SAPTaskIndex<<SAPExcelInfoI.taskStatusDesc;
    return WWYLPOST1;
}

ESS_Single *ESS_Single::GetInstance()
{
    if(ESS_SingleItiem != nullptr){
        return ESS_SingleItiem;
    }else{
        mutex.lock();
        ESS_SingleItiem=new ESS_Single;
        mutex.unlock();
        return ESS_SingleItiem;
    }
}


///////////////////////////////////////////////
/// \brief ESS_Single::initStationStatus
///初始化新马SMA 仓库中转点状态
/// 从deviceI表读取状态 在类构造时调用一次
void ESS_Single::initStationStatus()
{
    connectBuilder build(ASMORDERDBSTR);
    QSqlDatabase sqlDatabase =  build.getOpenDatabase();
    QSqlQuery sqlQuery(sqlDatabase);

    sqlQuery.setForwardOnly(true);
    sqlQuery.prepare("select * from deviceI where  enable =:enable;");
    sqlQuery.addBindValue(1);
    if(sqlQuery.exec())
    {
        while(sqlQuery.next())
        {
            //初始化站点
            /******************* 接驳台类型 **************/
            int status=sqlQuery.value("stationStatus").toInt();            //站点状态
            QString station=sqlQuery.value("deviceDesc").toString();          //站点名称

            stationStatusStruct stationItem;
            stationItem.station = station;
            stationItem.status = (stationStatusEnum)status;
            stationStatusMap[station] = stationItem;
        }
    }

}
/////////////////////////////////////////////////////////////////////////
/// \brief ESS_Single::getStationStatusByStationName
/// \param station
/// \param status
/// \return
///获取新马SMA 仓库站点状态
bool ESS_Single::getStationStatusByStationName(QString station, ESS_Single::stationStatusStruct &status) const
{
    if(stationStatusMap.contains(station))
    {
        status = stationStatusMap.value(station);
        return true;
    }
    return false;
}

/////////////////////////////////////////////////////////////////
/// \brief ESS_Single::getStationStatusMap
/// \return
///获取新马SMA 全部仓库站点状态
QMap<QString, ESS_Single::stationStatusStruct> ESS_Single::getAllStationStatusMap() const
{
    return stationStatusMap;
}
////////////////////////////////////////////////////////////////////////////
/// \brief ESS_Single::updateStationStatus
/// \param station
/// \param status
/// \return
///更新站点状态，包含更新到数据库
bool ESS_Single::updateStationStatus(QString station, ESS_Single::stationStatusEnum status)
{
    if(stationStatusMap.contains(station))
    {
        stationStatusMap[station].status = status;
        stationStatusMap[station].updateDateTime = QDateTime::currentDateTime();
        //更新到数据库
        connectBuilder build(ASMORDERDBSTR);
        QSqlDatabase sqlDatabase =  build.getOpenDatabase();
        QSqlQuery sqlQuery(sqlDatabase);

        sqlQuery.prepare("update deviceI set stationStatus = :stationStatus where deviceDesc =:deviceDesc;");
        sqlQuery.addBindValue(status);
        sqlQuery.addBindValue(station);
        if(sqlQuery.exec())
        {
            return true;
        }
    }
    return false;
}

void ESS_Single::setStationStatusMAP(QJsonValue value,QJsonArray rootFruitList)
{
    QJsonObject ReJson;
    QMap<QString, stationStatusStruct> stationStatusMap_;
    for(int i=0;i<rootFruitList.size();i++){
        ReJson=value[i].toObject();
        stationStatusStruct stationStatusStructI;
        stationStatusStructI.station=ReJson.value("stationId").toString();
        int status=ReJson.value("status").toInt();
        stationStatusStructI.status=(ESS_Single::stationStatusEnum)status;;
        stationStatusMap_.insert(stationStatusStructI.station,stationStatusStructI);
    }

    if(!stationStatusMap_.isEmpty()){
        updateStationStatusMAP(stationStatusMap_);
    }

}

bool ESS_Single::updateStationStatusMAP(QMap<QString, ESS_Single::stationStatusStruct> stationStatusMap_)
{
    //更新到数据库
    connectBuilder build(ASMORDERDBSTR);
    QSqlDatabase sqlDatabase =  build.getOpenDatabase();
    QSqlQuery sqlQuery(sqlDatabase);

    QMap<QString,stationStatusStruct>::iterator iter;
    foreach(stationStatusStruct iter,stationStatusMap_.values()){
        sqlQuery.prepare("update deviceI set stationStatus = :stationStatus where deviceDesc =:deviceDesc;");
        sqlQuery.addBindValue(iter.status);
        sqlQuery.addBindValue(iter.station);
        if(sqlQuery.exec())
        {
            if(stationStatusMap.contains(iter.station))
            {
                stationStatusMap[iter.station].status = iter.status;
                stationStatusMap[iter.station].updateDateTime = QDateTime::currentDateTime();
                qDebug()<<"平板更改库位状态-->station:"<<iter.station<<" status:"<<iter.status;
            }
        }else{
            return false;
        }
    }
    return true;
}

bool ESS_Single::getIOStatus(quint64 status, int index)
{
    if(index < 0 || index > 31)
        return false;
    return status & (0x00001 << (index-1));
}

void ESS_Single::setMoveTask(SAPExcelInfo SAPExcelInfoI, int station, QString taskType, int moveFlag, bool flag)
{
    // 创建 AGV 移动任务
    sapMsgInterface::getInstance()->PostTaskAgvMove(SAPExcelInfoI, station, taskType, moveFlag, flag);
}

void ESS_Single::setActionTask(SAPExcelInfo SAPExcelInfoI, int station, int actionCode, QString taskType, int moveFlag, bool flag)
{
    // 创建 AGV 动作任务
    sapMsgInterface::getInstance()->PostTaskAgvAction(SAPExcelInfoI, station, actionCode, taskType, moveFlag, flag);
}

void ESS_Single::setRunActionTask(SAPExcelInfo SAPExcelInfoI)
{
    // 创建 AGV 放行任务
    sapMsgInterface::getInstance()->PostTaskAgvRunAction(SAPExcelInfoI);
}

void ESS_Single::setCancelTask(SAPExcelInfo SAPExcelInfoI)
{
    // 创建 AGV 取消任务
    sapMsgInterface::getInstance()->PostTaskAgvCancel(SAPExcelInfoI);
}

void ESS_Single::setAgvMusicTask(int AgvNum, int MusicNum)
{
    // 创建 AGV 设置语音任务
    sapMsgInterface::getInstance()->PostTaskAgvMusic(AgvNum, MusicNum);
}

void ESS_Single::setAgvClearTraffControlTask(int AgvNum)
{
    // 创建 AGV 清除管制任务
    sapMsgInterface::getInstance()->PostTaskAgvClearTraffControlTask(AgvNum);
}

void ESS_Single::setAgvCancelTask(int AgvNum)
{
    // AGV 清除所有任务指令任务下发
    sapMsgInterface::getInstance()->PostTaskAgvCancelTask(AgvNum);
}

SAPExcelInfo ESS_Single::setSAPExcelInfo_New(QString taskType, QString taskTypeDesc, QString taskId, int agvNum, QString load, int loadPoint, QString unload, int unloadPoint)
{
    SAPExcelInfo SAPExcelInfoI;
    SAPExcelInfoI.taskType = taskType;
    SAPExcelInfoI.taskTypeDesc = taskTypeDesc;
    SAPExcelInfoI.taskId = taskId;
    SAPExcelInfoI.taskId_ess = "";
    SAPExcelInfoI.agvNum = QString::number(agvNum);
    SAPExcelInfoI.taskStatus = 0;
    QString taskTypeI=SAPExcelInfoI.taskType+"_"+QString::number(SAPExcelInfoI.taskStatus);
    SAPExcelInfoI.taskStatusDesc=ServerInitItem.taskStatusMap.value(taskTypeI);
    SAPExcelInfoI.load = load;
    SAPExcelInfoI.loadPoint = loadPoint;
    SAPExcelInfoI.unload = unload;
    SAPExcelInfoI.unloadPoint = unloadPoint;

    return SAPExcelInfoI;
}

void ESS_Single::Map_write()
{
    /********************************** 库位名称描述容器 **************************************/
    _StationNameDescMap.insert("BZ", "包装位");
    _StationNameDescMap.insert("SL1", "1线上料位");
    _StationNameDescMap.insert("CS1_1", "1线测试1号位");
    _StationNameDescMap.insert("CS1_2", "1线测试2号位");
    _StationNameDescMap.insert("CS1_3", "1线测试3号位");
    _StationNameDescMap.insert("HK1", "回库1号位");
    _StationNameDescMap.insert("HK2", "回库2号位");
    _StationNameDescMap.insert("HK3", "回库3号位");
    _StationNameDescMap.insert("HK4", "回库4号位");

    /********************************** 库位状态描述容器  越南语 **************************************/
    _StationStatusDescMap.insert(0, "无料架");
    _StationStatusDescMap.insert(1, "有料架");
    _StationStatusDescMap.insert(2, "满料架");
    _StationStatusDescMap.insert(3, "维护中");

    /********************************** 接口响应状态描述容器 **************************************/
    errorMsgMap.insert(-1, "非法值错误");
    errorMsgMap.insert(0, "任务创建成功");
    errorMsgMap.insert(1, "接料工位异常");
    errorMsgMap.insert(2, "对接工位异常");
    errorMsgMap.insert(3, "任务重复下发");
    errorMsgMap.insert(4, "任务无法放行");

    errorMsgMap.insert(100, "接收成功");

    _errorMsgMap.insert(-1, "非法值错误");
    _errorMsgMap.insert(0, "接收成功");
}

QString ESS_Single::Task_Count()
{
    if(_count >= 9)
    {
        _count = 0;
    }else
    {
        _count++;
    }

    return QString::number(_count);
}
